var ns,toast,db;
app = new Vue({
    el: '#app',
    data: {
        list: [], 
        //在线、离线模式
        lineStatus:1,//0 在线  1离线
        tasklist:[],
        pointlist:[],
        filelist:[],
    },
    methods: {
        onDealTime:function(Time){
            return ns.SetTime_style(Time);
        },
        get_data: function () {
            var that = this;
            let selplansql = `SELECT * FROM Sys_Plan WHERE PlanType=3 `;
            db.selectSql({
                name: 'prodemotest',
                sql: selplansql
            }, function (ret, err) {
                // console.log('SELECT-Sys_Plan')
                // console.log(JSON.stringify(ret))
                // console.log(JSON.stringify(err))
                if (ret.status) {
                    that.list = ret.data;
                    //任务未开始需要实时判断
                    that.checkTaskStatus();
                }
                // else {
                //     api.toast({
                //         msg: err,
                //         duration: 2000,
                //         location: 'bottom'
                //     });
                // }
            });
        },
         //获取任务超时,是否自动关闭任务
        //  getIsOutTime: function (ProjectID) {
        //     var that = this;
        //     let selconfigsql = `SELECT * FROM Sys_ProjectConfig WHERE ProjectID=${ProjectID} AND PlanType==3 AND ConfigKey='XGOutTime'`;
        //     db.selectSql({
        //         name: 'prodemotest',
        //         sql: selconfigsql
        //     }, function (ret, err) {
        //         if (ret.data.length > 0) {
        //             let configdata = ret.data[0];
        //             // that.IsOutTime = configdata.ConfigContent == '2' ? true : false;
        //         }
        //     });
        // },
        //判断任务-更改状态
        checkTaskStatus:function(){
            var that = this;
            if(that.list.length>0){
                that.list.forEach((item,index) => {
                    if (item.TaskStatus<3) {
                        let nowTime = moment().format('YYYY-MM-DD HH:mm');
                        // let nowTimeThird = moment().subtract(30, 'minutes').format('YYYY-MM-DD HH:mm');
                        const diffStartTime = moment(item.StartTime).diff(moment(nowTime), 'seconds');
                        const diffEndTime = moment(item.EndTime).diff(moment(nowTime), 'seconds');

                         //任务开始时间大于当前时间-执行中
                         if (diffStartTime <= 0) {
                            that.updateTaskStatus(item);
                        }
                        //获取任务超时,是否自动关闭任务
                        var IsOutTime = false;
                        let selconfigsql = `SELECT * FROM Sys_ProjectConfig WHERE ProjectID=${item.ProjectID} AND PlanType==3 AND ConfigKey='XGOutTime'`;
                        db.selectSql({
                            name: 'prodemotest',
                            sql: selconfigsql
                        }, function (ret, err) {
                            if (ret.data.length > 0) {
                                let configdata = ret.data[0];
                                IsOutTime = configdata.ConfigContent == '2' ? true : false;
                            }
                            //任务结束时间小于当前时间-漏巡
                            if (diffEndTime <= 0 && !IsOutTime) {
                                that.updateTaskIsMiss(item);
                            }   
                        });   
                    }
                });
            }
        },
        //变执行中时
        updateTaskStatus:function(item){
            var that = this;
            let strsql=`UPDATE Sys_Plan SET TaskStatus=2,TaskStatusDesc='执行中' WHERE ID=${item.ID}`;
            db.executeSql({
                name: 'prodemotest',
                sql: strsql
            }, function (ret, err) {
            });

            //当任务更新为执行中时 更新数据 判断是否按照巡更路线巡更 WithLine 0 否  1是
            if (item.WithLine == '1') {
                let strnextsql = `UPDATE Sys_PlanTask SET CanPunchCard='true'  WHERE ID in (SELECT ID FROM Sys_PlanTask  WHERE TaskStatus!=3 AND PlanTaskID=${item.ID} LIMIT 1 )`;
                db.executeSql({
                    name: 'prodemotest',
                    sql: strnextsql
                }, function (ret, err) {
                });
            }
            else {
                let strnextsqls = `UPDATE Sys_PlanTask SET CanPunchCard='true'  WHERE ID in (SELECT ID FROM Sys_PlanTask  WHERE TaskStatus!=3 AND PlanTaskID=${item.ID})`;
                db.executeSql({
                    name: 'prodemotest',
                    sql: strnextsqls
                }, function (ret, err) {
                });
            }
        },
         //变漏巡
         updateTaskIsMiss:function(item){
            var that = this;
            let strsql=`UPDATE Sys_Plan SET TaskStatus=4,TaskStatusDesc='已结束',IsMiss='true'  WHERE ID=${item.ID}`;
            db.executeSql({
                name: 'prodemotest',
                sql: strsql
            }, function (ret, err) {
            });
            let strtasksql=`UPDATE Sys_PlanTask SET TaskStatus=3,IsMiss='true'  WHERE ID in (SELECT ID FROM Sys_PlanTask  WHERE TaskStatus!=3 AND PlanTaskID=${item.ID})`;
            db.executeSql({
                name: 'prodemotest',
                sql: strtasksql
            }, function (ret, err) {
            });

            that.get_data();
        },
        doComplete:function(item){
            var that = this;
            var nowDate = moment().format('YYYY-MM-DD HH:mm');
            if(item.completeCount!=item.count){
                api.toast({
                    msg: '存在未完成的工作点，请完成所有工作点后再进行提交。',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            api.confirm({
                title: '提示',
                msg: '完成任务后不能再修改工作记录，如需修改需要使用重新执行功能。确认要完成工作任务吗？',
                buttons: ['确定', '取消']
            }, function (ret, err) {
                if (ret) {
                    if (ret.buttonIndex == 1) {
                        let strnextsql = `UPDATE Sys_Plan SET TaskStatus=3,TaskStatusDesc='已完成',CheckEndTime='${nowDate}'  WHERE ID=${item.ID}`;
                        db.executeSql({
                            name: 'prodemotest',
                            sql: strnextsql
                        }, function (ret, err) {
                            if (ret.status) {
                                that.get_data();
                            }
                        });
                    }
                }
            });
        }, 
        open_list: function (item) {
            var that = this;
            var url='renwulist_off_frm';
            var title = item.DevicePlanName;
            ns.openWin(url, title, {
                id: item.ID
            });
        },

        //在线-离线模式切换
        open_change_line: function () {
            let that=this;
            //获取当前网络状态
            api.getNetworkType({
                success: function(res) {
                    if(res.networkType!="none"){
                        //有网  当离线切换在线时  任务存在需要判断是否上传任务  上传成功后需要清空任务
                        //有网  当在线切换离线时  覆盖并创建任务
                        let message= that.lineStatus==0?'离线':'在线';
                        api.confirm({
                            title: '提示',
                            msg: '是否切换'+message+'模式?',
                            buttons: ['确定', '取消']
                        }, function(ret, err) {
                            // console.log(JSON.stringify(ret));
                            if (ret.buttonIndex == 1) {
                                that.doTaskData(1);  
                            }
                            if (ret.buttonIndex == 2) {
                                return;
                            }     
                        });
                    }else{
                        api.toast({
                            msg: '请联网，只能在有网的情况下进行模式切换！',
                            duration: 2000,
                            location: 'bottom'
                        });
                        return;
                    }   
                }
            });
        },
        // 切换在线模式 上传任务-调用接口
        doTaskData:function(UploadType){
            var that = this;
            if(UploadType==1){
                if(that.list.length<=0){
                    api.setPrefs({
                        key: 'lineStatus',
                        value: 0
                    });
                    api.addEventListener({
                        name:'viewdisappear'
                    }, function(ret, err){        
                       api.closeWin();
                    });
                    ns.openWin('patrolplan_renwulist',"安防巡更待办");      
                    return;
                }
                else{
                    that.doSelectData();  
                }    
            }
            if (UploadType == 2) {
                api.getNetworkType({
                    success: function (res) {
                        if (res.networkType != "none") {
                            if (that.list.length <= 0) {
                                api.toast({
                                    msg: "没有可上传的离线任务，请切换在线模式进行下载！",
                                    duration: 2000,
                                    location: 'bottom'
                                });
                                return;
                            }
                            else{
                                that.doSelectData();
                            }
                        }
                        else {
                            api.toast({
                                msg: '请联网，只能在有网的情况下进行模式切换！',
                                duration: 2000,
                                location: 'bottom'
                            });
                            return;
                        }
                    }
                })
            }
        },  
        doSelectData:function(UploadType){
            var that = this;
            //取执行中和已完成的数据上传接口
            let selplansql = `SELECT * FROM Sys_Plan WHERE PlanType=3 AND TaskStatus!=1`;
            db.selectSql({
                name: 'prodemotest',
                sql: selplansql
            }, function (ret, err) {
                if (ret.status) {
                    that.tasklist = ret.data;
                }
            });
            let seltasksql = `SELECT * FROM Sys_PlanTask where PlanTaskID in (SELECT ID FROM Sys_Plan WHERE PlanType=3 AND TaskStatus!=1) `;
            db.selectSql({
                name: 'prodemotest',
                sql: seltasksql
            }, function (ret, err) {
                if (ret.status) {
                    that.pointlist = ret.data;
                }
            });
            let selfilesql = `SELECT * FROM Sys_File WHERE PlanTaskID in (SELECT ID FROM Sys_Plan WHERE PlanType=3 AND TaskStatus!=1) AND ID=0`;
            db.selectSql({
                name: 'prodemotest',
                sql: selfilesql
            }, function (ret, err) {       
                if (ret.status) {
                    that.filelist = ret.data;
                }
            });
            that.doUploadTask(UploadType);//调用接口
        },
        doUploadTask: function (UploadType) {
            var that = this;
            api.confirm({
                title: '提示',
                msg: '成功后会清空离线任务，确定?',
                buttons: ['确定', '取消']
            }, function (ret, err) {
                if (ret.buttonIndex == 1) {
                    //判断传给接口的计划任务数据是否存在
                    if(that.tasklist.length<=0){
                        let resdel=that.doTaskClearOff();
                        if (resdel) {
                            api.setPrefs({
                                key: 'lineStatus',
                                value: 0
                            });
                            api.addEventListener({
                                name:'viewdisappear'
                            }, function(ret, err){        
                               api.closeWin();
                            });
                            ns.openWin('patrolplan_renwulist',"安防巡更待办");      
                            return;
                        }
                        return;
                    }
                    var options = {};
                    options.action = "saveofftaskdata";//saveequipmenttaskdevicedata
                    options.tasklist = JSON.stringify(that.tasklist);
                    options.pointlist = JSON.stringify(that.pointlist);
                    options.filelist = JSON.stringify(that.filelist);
                    var fileform= {};
                    if(that.pointlist.length>0){
                        that.pointlist.forEach((item,index) => {
                            let fileName="file-"+item.ID
                            let fileOffList = that.filelist.filter( (val) => {
                                return val.TaskID == item.ID;
                            });
                            let FilePathList = fileOffList.map((val) => {
                                return val.FilePath;
                            })
                            if(FilePathList.length>0){
                                fileform[fileName]=FilePathList;
                            }     
                        });
                    }
                    ns.post(options, function (succeed, data, err) {
                        if (succeed) {
                            let resdel=that.doTaskClearOff();
                            if (resdel) {
                                api.setPrefs({
                                    key: 'lineStatus',
                                    value: 0
                                });
                                api.addEventListener({
                                    name:'viewdisappear'
                                }, function(ret, err){        
                                   api.closeWin();
                                });
                                ns.openWin('patrolplan_renwulist',"安防巡更待办");      
                                return;
                            }
                        } else if (err) {
                            api.toast({
                                msg: err,
                                duration: 2000,
                                location: 'bottom'
                            });
                        }
                    }, {
                        toast: true,
                        files: fileform
                    });
                }
                if (ret.buttonIndex == 2) {
                    return;
                }
            });
        },
        //清空离线任务
        doTaskClearOff: function () {
            let delconfigdsql=`DELETE FROM Sys_ProjectConfig WHERE PlanType=3`; 
            let delstandardsql=`DELETE FROM Sys_TaskStandard WHERE PlanTaskID in (SELECT ID FROM Sys_Plan WHERE PlanType=3)`; 
            let delfilesql = `DELETE FROM Sys_File WHERE PlanTaskID in (SELECT ID FROM Sys_Plan WHERE PlanType=3) `;
            let deltasksql = `DELETE FROM Sys_PlanTask WHERE PlanTaskID in (SELECT ID FROM Sys_Plan WHERE PlanType=3) `;
            let delplansql = `DELETE FROM Sys_Plan WHERE PlanType=3 `;
            db.executeSql({
                name: 'prodemotest',
                sql: delconfigdsql,
            }, function (ret, err) {
            });
            db.executeSql({
                name: 'prodemotest',
                sql: delstandardsql,
            }, function (ret, err) {
            });
            db.executeSql({
                name: 'prodemotest',
                sql: delfilesql,
            }, function (ret, err) {
            });
            db.executeSql({
                name: 'prodemotest',
                sql: deltasksql,
            }, function (ret, err) {

            });
            db.executeSql({
                name: 'prodemotest',
                sql: delplansql,
            }, function (ret, err) {
            });
            return true;
        },
    }
});
apiready = function () {
    api.parseTapmode();
    ns = window.Foresight.Util;
    toast = new auiToast();
    db = api.require('db');

    db.openDatabase({
        name: 'prodemotest'
    }, function(ret, err) {
        if (!ret.status) {
            api.toast({
                msg: err,
                duration: 2000,
                location: 'bottom'
            });
        } 
        else{
            app.get_data();
        }  
    });

    // 监听当前window页面显示
    api.addEventListener({
        name: 'viewappear'
    }, function (ret, err) {
        // 允许屏幕休眠
        api.setKeepScreenOn({
            keepOn: false
        });
    });
    //在线-离线模式切换
    api.addEventListener({
        name: 'do_change_line'
    }, function (ret, err) {
        app.open_change_line();
    });

    api.addEventListener({
        name: 'reloadtaskoff'
    }, function (ret, err) {
        app.get_data();
    });

    api.addEventListener({
        name: 'home-refresh'
    }, function (ret, err) {
        app.get_data();
    });

};
